import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {createPage, base, ajax, toast} from 'nc-lightapp-front';
import {languageCreateUIDOM, hrAjax, getQueryCondition} from 'src/hrpub/common/utils/utils';

const {NCAffix, NCModal} = base

const {Body, Header: NCModalHeader} = NCModal;
import WpsDownload from "../components/wpsModal/index";
import ReferSearch from "../../../../hrpub/common/components/referSearch/org";
import './index.less'
// import PsnCardGridRef from '../../../refer/PsnCardGridRef';
import download from '../../../../hrpub/common/utils/download/download';
// import ViewCard from 'src/hrpub/common/components/card-view';
// 初始化处理template数据
const unitConf = {
    multiLang: {
        domainName: 'uapbd',
        currentLocale: 'zh-CN',
        moduleId: 'refer_uapbd',
    },
    key: 'pk_org',
    refType: 'tree',
    refName: 'refer-000176', /* 国际化处理： 行政组织*/
    placeholder: 'refer-000176', /* 国际化处理： 行政组织*/
    refCode: 'uapbd.org.AdminOrgDefaultTreeRef',
    queryTreeUrl: '/nccloud/riaorg/ref/AdminOrgDefaultTreeRef.do',
    treeConfig: {name: ['refer-000002', 'refer-000003'], code: ['refcode', 'refname']}, /* 国际化处理： 编码,名称*/
    rootNode: {refname: 'refer-000176', refpk: 'root'}, /* 国际化处理： 行政组织*/
    isMultiSelectedEnabled: false
};

const countryConf = {
    multiLang: {
        domainName: 'uapbd',
        currentLocale: 'zh-CN',
        moduleId: 'refer_uapbd',
    },
    key: 'pk_country',
    refType: 'grid',
    refName: 'refer-000444', /* 国际化处理： 国家地区EX*/
    placeholder: 'refer-000444', /* 国际化处理： 国家地区EX*/
    refCode: 'uapbd.refer.pubinfo.CountryExDefaultGridRef',
    queryGridUrl: '/nccloud/uapbd/pub/CountryExDefaultGridRef.do',
    isMultiSelectedEnabled: false,
    columnConfig: [{
        name: ['refer-000002', 'refer-000441', 'refer-000003', 'refer-000422', 'refer-000442', 'refer-000443', 'refer-000445'], /* 国际化处理： 编码,三位代码,名称,描述,时区,格式,欧盟国家*/
        code: ['refcode', 'codeth', 'refname', 'description', 'timezonename', 'formatname', 'iseucountry'],
        checked: {
            description: false,
            timezonename: false,
            formatname: false,
            iseucountry: false,
        }
    }]
};

class PsndocCardRpt extends Component {
    constructor(props) {
        super(props);
        if (props.use) {
            props.use.editTable('list');
            props.use.search('query');
        }
        this.config = props.config
        this.staticUrl = {
            CardrptQueryAction: '/nccloud/hrhi/cardrep/CardrptQueryAction.do', //查询列表
            PsndocCardReptQueryAction: '/nccloud/hrhi/psndoc/PsndocCardReptQueryAction.do', //卡片阅览
            DownloadCard:'/nccloud/hrhi/rptfef/ReportDownloadFilesAction.do'//下载卡片
        }

        this.state = {
            previewVisible: false,
            previewHtml: '',
            psnCard: null,
            selRecord: {},
            node_type: props.config.node_type,
            conditions: null,
            pk_org: null,
            orgVal: null,
            oid: null,
            allPsnPk: '',
            selRow: 0,
            pageHeight: 0,
            json: {},
            pkDocs:'',
            wpsInitmodelVisible:false
        };

        this.getData = this.getData.bind(this)
        this.handleButtonClick = this.handleButtonClick.bind(this)
        this.getTableData = this.getTableData.bind(this)
        this.cardviewAction = this.cardviewAction.bind(this)
        this.onRowClick = this.onRowClick.bind(this)
        this.setCardViewDisable = this.setCardViewDisable.bind(this)
        this.handleQueryMeta = this.handleQueryMeta.bind(this)
        // this.showCardPreview = this.showCardPreview.bind(this);
        // this.downloadCard = this.downloadCard.bind(this);
        // this.selectPsnCard = this.selectPsnCard.bind(this);
        // props.createUIDom(this.config, data => {
        //     this.props.meta.setMeta(data && data.template ? data.template : {});
        //     this.props.button.setButtons(data && data.button ? data.button : {});
        // })
    }

    componentDidMount() {
        const {appcode, pagecode} = this.props.config
        languageCreateUIDOM(this.props)({appcode, pagecode}, {moduleId: 'hi6007', domainName: 'hrhi'}, (data, lang) => {
            this.props.meta.setMeta(data && data.template ? data.template : {});
            this.props.button.setButtons(data && data.button ? data.button : {});
            this.setState({
                json: lang
            }, () => {
                // window.location.hash =
                //     `?&c=${this.props.config.appcode}&p=${this.props.config.pagecode}&ar=0001Z510000000065KV7&id=0`;
                let height = document.documentElement.clientHeight;
                this.setState({pageHeight: height - 62});
                this.setCardViewDisable()
            })
        })
    }

    getData(obj) {
        let params = JSON.parse(JSON.stringify(obj))
        this.setState({
            pk_org: params.refpk,
            orgVal: params
        }, () => {
            this.setCardViewDisable()
        })
    }

    empty() {
    }

    setCardViewDisable() {
        this.props.button.setButtonDisabled({
            'query': this.state.pk_org ? false : true,
            'refresh': this.state.pk_org ? false : true,
            'cardview': this.state.oid ? false : true,
            'export': this.state.oid ? false : true
        })
    }

    getTableData() {
        let {conditions, node_type, oid, pk_org} = this.state
        ajax({
            url: this.staticUrl.CardrptQueryAction,
            data: Object.assign({}, {...conditions, node_type, pk_org}),
            success: res => {
                if (res.success) {
                    let psnPks = []
                    let data
                    if (res.data && res.data.grid) {
                        data = res.data.grid.list
                    } else {
                        data = {rows: []}
                    }
                    let msg = res.data && res.data.msg
                    if (msg) {
                        toast({'color': 'warning', content: msg})
                    }
                    this.props.editTable.setTableData('list', data);
                    if (data.rows) {
                        for (let i of data.rows) {
                            psnPks.push(i.values.pk_psndoc.value)
                        }
                    }
                    this.setState({
                        allPsnPk: psnPks.join('_')
                    })
                }
            }
        })
    }

    clickSearchBtn() {
        let queryParam = this.props.search.getQueryInfo('query')
        let oid = queryParam.oid
        let conditions = getQueryCondition(this.props, 'query')
        this.setState({
            oid, conditions
        }, () => {
            this.getTableData()
            this.setCardViewDisable()
        })
    }

    cardviewAction() {
        let {allPsnPk, selRow, pk_org} = this.state
        ajax({
            url: this.staticUrl.PsndocCardReptQueryAction,
            data: Object.assign({}, {allPsnPk, selRow, pk_org}),
            success: res => {
                if (res.success && res.data) {
                    let location = window.location
                    location.port ? window.open("uclient://start/http://" + location.hostname + ":" + location.port + res.data) : window.open("uclient://start/http://" + location.hostname + res.data)
                }
            }
        })
    }

    /**
     * 处理query meta
     * @param {string} pk_org
     * @param {Object} props
     */
    handleQueryMeta(pk_org, props) {
        let metas = props.meta.getMeta()
        let queryItems = metas.query
        queryItems.items.forEach(item => {
            switch (item.attrcode) {
                case 'hi_psnjob.trnstype':
                    item.queryCondition = function () {
                        return {
                            isShowDisable: true
                        }
                    };
                    break;
                case 'hi_psnjob.clerkcode':
                    item.queryCondition = {
                        pk_org: pk_org,
                        func_type: 4,
                        GridRefActionExt: 'nccloud.web.hrhi.psndoc.sqlbuilder.PsndocQryDlgPsnRefSqlBuilder'
                    }
                    if(props.config.node_type === '0') item.queryCondition['funcPK'] = '@@@@Z710000000006M3L'
                    break;
                case 'hi_psnjob.pk_dept':
                case 'hi_psnjob.pk_post':
                    unitConf.queryCondition = () => {
                        return {
                            pk_org: pk_org,
                            TreeRefActionExt: 'nccloud.web.hrhi.pub.sqlbuilder.OrgRefNoPowerSqlBuilder'
                        }
                    };
                    item.isShowUnit = true;
                    item.unitProps = unitConf;
                    break;
                case 'hi_psndoc_psnchg.comecorpaddr':
                case 'hi_psndoc_psnchg.tocorpaddr':
                case 'nativeplace':
                case 'permanreside':
                    item.isShowUnit = true;
                    item.unitProps = countryConf;
                    break;
                default:
                    break;
            }
        });
        props.meta.setMeta(metas);
    }

    handleButtonClick(props, type) {
        switch (type) {
            case 'query':
                this.handleQueryMeta(this.state.pk_org, props)
                props.search.openAdvSearch('query', true);
                break;
            case 'cardview':
                // this.cardviewAction()
                // 下面是弹窗展示预览调用函数
                this.showCardview();
                break;
            case 'refresh':
                this.getData({refpk: this.state.pk_org})
                break;
            // case 'export':
            //     this.downloadCard();
            //     break;
        }
    }

    // 展示卡片预览弹窗, 缺接口中
    // showCardPreview() {
    //     let {psnCard, selRecord} = this.state;
    //     let psnPk = selRecord.values ? selRecord.values.pk_psnjob.value : '';
    //     let cardPk = psnCard.values['hr_rpt_def.pk_rpt_def'].value;

    //     ajax({
    //         url: '/nccloud/hrhi/cardrep/CardrptPreviewAction.do',
    //         data: {
    //             pk_rpt_def: cardPk,
    //             pk_psnjob: psnPk
    //         },
    //         success: res => {
    //             if (res.success && res.data) {
    //                 // let location = window.location
    //                 // location.port ? window.open("uclient://start/http://"+location.hostname+":"+location.port+res.data):window.open("uclient://start/http://"+location.hostname+res.data)
    //                 this.setState({
    //                     previewVisible: true,
    //                     previewHtml: res.data
    //                 });
    //             }
    //         }
    //     })
    // }

    // 下载人员人员信息
    // downloadCard() {
    //     let {psnCard, selRecord} = this.state;

    //     let psnPk = selRecord.values ? selRecord.values.pk_psnjob.value : '';
    //     let cardPk = psnCard.values['hr_rpt_def.pk_rpt_def'].value;

    //     download({
    //         url: '/nccloud/hrhi/cardrep/CardrptExportAction.do',
    //         body: {
    //             jsonStr: JSON.stringify({
    //                 pk_rpt_def: cardPk,
    //                 pk_psnjob: psnPk
    //             })
    //         },
    //         onResult: (res) => {

    //         }
    //     });
    // }

    // 选择人员卡片
    // selectPsnCard(value) {
    //     this.setState({
    //         psnCard: value
    //     });
    // }

    onRowClick(props, name, record, index) {
        this.setState({
            selRow: index,
            selRecord: record
        })
    }

    //联查卡片
    showCardview() {
        const {editTable} = this.props;
        let listData = editTable.getCheckedRows('list');
        if(listData.length === 0){
            toast({'color': 'warning', content: "请选择人员"})
            return 
        }
        let result = listData.map(item=>{
            return item.data.values['pk_psndoc'].value
        })
        let resultStr = result.join(',')
        this.setState({
            pkDocs:resultStr,
            wpsInitmodelVisible:true
        })

    }
    closeWps (){
        this.setState({
            pkDocs:'',
            wpsInitmodelVisible:false
        })
    }
    render() {
        const {button, search, editTable, form, modal, cardPagination} = this.props;
        const {createButtonApp} = button;
        let {createEditTable} = editTable;
        let {NCCreateSearch} = search;
        let param = {
            showFlag: true
        }
        return (
            <div>
                <NCAffix>
                    <div className="header">
                        <ReferSearch
                            param={param}
                            orgVal={this.state.orgVal}
                            ref="sn-refer-search"
                            getOrgData={this.getData}/>
                        {/* <span style={{
                            marginLeft: '8px'
                        }}>
                            {this.state.orgVal && <PsnCardGridRef
                                queryCondition={() => {
                                    return {
                                        rpt_type: "1",
                                        pk_org: this.state.orgVal ? this.state.orgVal.refpk : ''
                                    }
                                }}
                                value={this.state.psnCard}
                                onChange={this.selectPsnCard}
                            />}
                        </span> */}
                        <div className=" btn-group">
                            {
                                createButtonApp({
                                    area: 'head', //如果页面中的有多个区域有按钮，这里的area当做筛选条件，只渲染按钮的后台数据中area字段为这里指定值的按钮；
                                    // buttonLimit: 5, // buttongroup 类型的按钮默认是平铺展示，指定了buttonLimit后，超出指定值的按钮将收入到'更多下拉中'
                                    onButtonClick: this.handleButtonClick.bind(this)
                                })
                            }
                        </div>
                    </div>
                </NCAffix>
                <div className="sn-region-container" style={{height: this.state.pageHeight}}>
                    {
                        createEditTable('list', {
                            showCheck: true,
                            showIndex: true,
                            adaptionHeight: true,
                            cancelCustomRightMenu: true,
                            multipleRowCell: true,
                            onRowClick: this.onRowClick
                        })
                    }
                </div>
                <div style={{display: 'none'}}>
                    {
                        this.state.json ? (NCCreateSearch('query', {
                            clickSearchBtn: this.clickSearchBtn.bind(this),
                            onlyShowAdvArea: false,
                            showAdvSearchPlanBtn: true,
                            saveSearchPlan: true,
                            onlyShowSuperBtn: true,
                            // clickAdvBtnEve: ()=>{},
                            queryCondition: () => {
                                return {...this.state.searchParam}
                            },
                            searchBtnName: this.state.json['hi6007-000004'],
                            replaceSuperBtn: this.state.json['hi6007-000004']/* 国际化处理： 查询*/
                        })) : null
                    }
                </div>
                {/* 联查卡片 */}
                <WpsDownload
                     close = {this.closeWps.bind(this)}
                     wpsInitmodelVisible = {this.state.wpsInitmodelVisible}
                     pk_psndoc={this.state.pkDocs}
                     pk_org = {this.state.orgVal}
                     language = {this.state.json}
                ></WpsDownload>
                {/* <NCModal
                    show={this.state.previewVisible}
                    onHide={() => {
                        this.setState({
                            previewVisible: false
                        });
                    }}
                    size="max"
                    className="card-preview-modal"
                >
                    <NCModalHeader closeButton={true}></NCModalHeader>
                    <Body>
                        <div style={{
                            textAlign: 'center'
                        }}>
                            <span
                                className="card-preview-iframe"
                                dangerouslySetInnerHTML={{
                                    __html: this.state.previewHtml
                                }}
                            >
                            </span>
                        </div>
                    </Body>

                </NCModal> */}
            </div>
        )
    }
}

export default PsndocCardRpt
